const QuestionType = require('../models/questionType');
const {Op} = require('sequelize');
class QuestionTypesCtl{
  //查看题型种类
  async find(ctx){
    const {count,rows} = await QuestionType.findAndCountAll();
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  //增加题型
  async create(ctx){
    ctx.verifyParams({
      type_name:{ type:'string', required:true }
    })
    //获取请求体中的题型名称
    const { type_name } = ctx.request.body;
    //查重
    const repeatedQuestionType = await QuestionType.findOne({
      where:{
        type_name:type_name
      }
    })
    if(repeatedQuestionType){
      ctx.throw(409,"已有此题型");
    }
    const questionType = await QuestionType.create({
      type_name:type_name
    })
    ctx.body = questionType;
  }
  //修改题型
  async update(ctx){
    const questionType = await QuestionType.findOne({
      where:{
        type_id:ctx.params.id
      }
    });
    if(!questionType){ctx.throw(404,'当前题型不存在');}
    const { type_name } = ctx.request.body;
    const repeatedQuestionType = await QuestionType.findOne({
      where:{
        [Op.and]:[{
          type_id:{
            [Op.ne]:ctx.params.id
          }
        },{
          type_name:type_name
        }]
      }
    })
    if(repeatedQuestionType){ctx.throw(409,'已存在此题型')}
     await QuestionType.update({
      type_name:type_name
    },{
      where:{
        type_id:ctx.params.id
      }
    })
    ctx.body = { questionType:type_name }
  }
  //删除题型
  async delete(ctx){
    const questionType = await QuestionType.findOne({
      where:{
        type_id:ctx.params.id
      }
    });
    if(!questionType){ctx.throw(404,'题型不存在');}
    await questionType.destroy();
    ctx.status = 204
  }
}
module.exports = new QuestionTypesCtl();